package com.heeexy.example.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.heeexy.example.dao.TeacherDao;
import com.heeexy.example.dao.UserDao;
import com.heeexy.example.dto.TeacherInfo;
import com.heeexy.example.dto.UserEntity;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @Author MyPC
 * @Date 2022/3/28 14:29
 * @description：
 * @Version 1.0
 */
@Slf4j
public class ExeclDataListener implements ReadListener<TeacherInfo> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;

    /**
     * 缓存的数据
     */
    private List<TeacherInfo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private List<UserEntity> entityList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */

    private TeacherDao teacherDao;

    private UserDao userDao;

    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *
     * @param teacherDao
     */

    public ExeclDataListener(TeacherDao teacherDao,UserDao userDao) {
        this.teacherDao = teacherDao;
        this.userDao = userDao;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param teacherInfo                 one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param teacherInfo,analysisContext
     */
    @Override
    public void invoke(TeacherInfo teacherInfo, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", teacherInfo.toString());
        if (teacherInfo.getTusername() == null || "".equals(teacherInfo.getTusername()) || teacherInfo.getTname() == null || "".equals(teacherInfo.getTname())) {
            log.debug("数据为空！");
        } else {
            cachedDataList.add(teacherInfo);
        }
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
            entityList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！" + cachedDataList.size());
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        insertUsers();
        log.info("存储数据库成功！");

    }

    /**
     * 先插入User用户 再 写入老师数据
     */
    private void insertUsers() {
//        List<UserEntity> entityList = new ArrayList<>();;
        cachedDataList.forEach(item->{
            UserEntity entity  = new UserEntity();
            entity.setNickname(item.getTname());
            entity.setUsername(item.getTusername());
            entity.setPassword(item.getTpassword());
            entity.setRoleid(2);
            entityList.add(entity);
        });

        userDao.insertUsers(entityList);
        userDao.insertBatchUserRole(entityList);
        log.info("{}条数据，开始存储sys_user数据库表！", entityList.size());
        for (int i = 0; i <entityList.size() ; i++) {
            if (entityList.get(i).getId()!=0 ) {
                cachedDataList.get(i).setUid(entityList.get(i).getId());
            }
        }
        teacherDao.insertBatch(cachedDataList);
        log.info("{}条数据，开始存储teacher_info数据库表！", cachedDataList.size());
    }
}
